from rest_framework import serializers, exceptions

from api.models import Book


class BookModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        # fields应该写哪些字段  应该填写序列化与反序列化所需字段的并集
        fields = ("book_name", "price", "publish", "authors", "pic")
        extra_kwargs = {
            "book_name": {
                "required": True,  # 必填字段
                "min_length": 2,  # 最小长度
                "error_messages": {
                    "required": "图书名必须提供",
                    "min_length": "图书名不能少于两个字符",
                }
            },
            # 指定某个字段只参与序列化
            "pic": {
                "read_only": True
            },
            # 指定某个字段只参与反序列化
            "publish": {
                "write_only": True
            },
            "authors": {
                "write_only": True
            },
        }
    def validate(self,attrs):
        print(attrs,"验证全局钩子")
        return attrs
    def validate_book_name(self, obj):
        obj_name = Book.objects.filter(book_name = obj)
        if obj_name:
            raise exceptions.ValidationError("书名已经存在")
        return obj

    #可以自定义更新
    # def update(self, instance, validated_data):
    #     print(instance,'实例')
    #     print(validated_data,'实例数据')
    #     return instance